var app = sm("do_App");
var page = sm("do_Page");
var nf = sm("do_Notification");
var easemob = sm("do_Easemob");
var device = sm("do_Device");
var imUrl = require("url/im");
var http = require("helper/http");
var httpSilence = require("helper/httpSilence");
var imHelper = require("helper/im");
var time = require("util/time");
var rootView = ui("$");
var myImId,myName, myLogo, herImId, herName, herLogo,herUserId;
var chatList = ui("chatList");
var chatListData = mm("do_ListData");
chatList.bindItems(chatListData);

//开始查询的起点message的Id，如果不填的话默认从最新的一条开始【通过组件取历史消息需要传入这个参数】
var messageId4QueryLast = null;
var lastMsgTime = null;//最早的历史消息的时间
/**
 * time_line source://view/im/chat/cell/timeLine.ui,
 * her_text source://view/im/chat/cell/left_text.ui,
 * my_text source://view/im/chat/cell/right_text.ui,
 * her_pic source://view/im/chat/cell/left_pic.ui,
 * my_pic source://view/im/chat/cell/right_pic.ui,
 * her_audio source://view/im/chat/cell/left_audio.ui,
 * my_audio source://view/im/chat/cell/right_audio.ui
 */
//模板序号
var time_line_template = 0;
var her_text_template = 1,my_text_template = 2;
var her_pic_template = 3,my_pic_template = 4;
var her_audio_template = 5,my_audio_template = 6;


var startTime = 1430413261171;//开始时间2015-05-01 01:01:01.171

//获取聊天对象
//（从chat.ui执行 page.fire({name:"transport", data:imUser})传送参数过来）
page.on("transport", function(imUserData) {
	//加载他的im信息
	herImId = imUserData.imId;
	herName = imUserData.name;
	herLogo = imUserData.logo;
	herUserId = imUserData.userId;
	//加载我的im信息
	imHelper.loadMe(function(myImUser){
		myImId = myImUser.imId;
		myName = myImUser.name;
		myLogo = myImUser.logo;
		load20HistoryMessage();//加载历史对话
	});
	
})

//通过组件方法取--单聊--最近20条历史消息
function load20HistoryMessage(){
	var param ={conversationId : herImId,	chatType: "Chat",maxCount: 20, messageId: ""};
	easemob.getConversation(param,function(messageList){
		deviceone.print(JSON.stringify(messageList), "单聊--最近20条消息");
		if(messageList && messageList.length>0){
			messageId4QueryLast = messageList[0].messageId;//更多消息的查询起点【类似分页查询】
			showMessageBefore(messageList,true);
		}
		if(messageList.length <=1){
			loadMoreHistoryMessage(messageId4QueryLast);//如果很少数据，尝试加载更多
		}
	});
}

var isAlertEnd4Msg = false;//是否已提示【没有更多历史消息了】
//通过组件方法取--单聊--更多历史消息
function loadMoreHistoryMessage(lastMessageId){
	if(lastMessageId==null || lastMessageId =="undefined"){
		return;
	}
	var param ={conversationId : herImId,	chatType: "Chat",maxCount: 10, messageId: lastMessageId};
	easemob.getConversation(param,function(messageList){
		deviceone.print(JSON.stringify(messageList), "单聊--更多消息");
		if(messageList && messageList.length>0){
			messageId4QueryLast = messageList[0].messageId;//更多消息的查询起点【类似分页查询】
			showMessageBefore(messageList,false);
		}else{
			if(!isAlertEnd4Msg){
				setTimeLine4LastOneMsg();//显示最早一条历史消息的时间
				isAlertEnd4Msg = true;
				insertOneMessage2Top({template : time_line_template,time : "没有更多消息了"});
				chatList.refreshItems();
			}	
		}
	});
}

//弹出 相机或拍照 菜单
var addPicMenu = rootView.add("picMenu", "source://view/im/menu/picMenu.ui", 0, 0);
var picMenuBg = ui(addPicMenu+".picMenuBg");
page.on("im_to_select_image", function() {
	page.hideKeyboard();
	picMenuBg.visible = true;
});

//隐藏图片选择窗口
page.on("hide_select_image_div", function() {
	picMenuBg.visible = false;
});

page.on("im_to_select_image_back", function(imgList) {
	//deviceone.print(imgList,"imgList:");
	sendImgMessage(imgList);
});
page.on("im_to_send_audio", function(audioFile) {
	sendAudioMessage(audioFile);
});

/***********************监听**begin********************************/
page.on("im_to_send_text", function(data, e) {
	sendTextMessage(data);
})

// 弹出键盘时将聊天页面滚动到底
page.on("focusIn", function(data, e) {
	picMenuBg.visible = false;
	scroll2ListEnd();
})
// 点击聊天页面时隐藏键盘【当有聊天内 容之时才生效，如果页面空白，点击没么应】
rootView.on("touch", function(data, e) {
	page.hideKeyboard();
})



//消息头字段
var chatType, messageId, conversationId, from, to, timestamp;
//消息body字段
var body_type, body_text, remotePath, localPath, thumbnailRemotePath, thumbnailLocalPath,latitude, longitude, address, fileLength, duration;
app.off("im_comming_messages4gchat");
app.on("im_comming_messages4chat", function(data) {
	showCommingMsg(data);
})

//发送文本消息
function sendTextMessage(textContent){
	if(textContent.length==0){
		nf.toast("请输入内容!");
		return;
	}
	easemob.sendTextMessage({
		username : herImId,
		text : textContent,
		chatType : "Chat"
	}, function(data) {
		setTimeLine4Dynamic(new Date().getTime());//设置时间间隔线
		appendOneMessage2End({
			template : my_text_template,
			text : textContent,
			logo : myLogo,
			messageId: new Date().getTime()
		});
		chatList.refreshItems();
		scroll2ListEnd();
		page.hideKeyboard();
		fireSendingMessage("0",textContent,{path:"",len:0});//触发“发送消息”
	});
}

//滚动到列表底部
function scroll2ListEnd(){
	if(chatListData.getCount()>0){
		chatList.scrollToPosition(chatListData.getCount()-1, false);
	}
}

//发送多张图片
function sendImgMessage(imgList){
	if(imgList.length==0){
		return;
	}
	for(var i=0;i<imgList.length;i++){
		sendOneImgMessage(imgList[i]);
	}
};

//发送一张图片
function sendOneImgMessage(imgPath) {
	easemob.sendMediaMessage({
		username : herImId,
		messageType : 0, //包括0.图片(Image)，1.语音(Voice)，2.视频(Video)，3.文件(File)
		path : imgPath,//图片本地路径
		title : "图片",
		chatType : "Chat"
	}, function(data, e) {
		setTimeLine4Dynamic(new Date().getTime());//设置时间间隔线
		appendOneMessage2End({
			template : my_pic_template,
			text : "",
			pictrue : imgPath,
			logo : myLogo,
			messageId: new Date().getTime() //发消息没有messageId,用当前时间代替
		});
		chatList.refreshItems();
		scroll2ListEnd();
		fireSendingMessage("1","图片",{path:imgPath,len:0});//触发“发送消息”
	});
}

//发送语音
function sendAudioMessage(audioFile){
	easemob.sendMediaMessage({
		username : herImId,
		messageType : 1, //包括0.图片(Image)，1.语音(Voice)，2.视频(Video)，3.文件(File)
		path : audioFile.filePath,//语音本地路径
		title : "语音",
		chatType : "Chat"
	}, function(data, e) {
		setTimeLine4Dynamic(new Date().getTime());//设置时间间隔线
		appendOneMessage2End({
			template : my_audio_template,
			text : audioFile.fileLen+"\"",//语音长度（秒）
			voiceLen : audioFile.fileLen, 
			voice : audioFile.filePath,//语音本地路径(用于显示)
			logo : myLogo,
			messageId: new Date().getTime() //发消息没有messageId,用当前时间代替
		});
		chatList.refreshItems();
		scroll2ListEnd();
		fireSendingMessage("3","语音",{path:audioFile.filePath,len:audioFile.fileLen});//触发“发送消息”
		imHelper.playXiu();
	});
	
}
/**
 * {"chatType":"消息类型,包括Chat(单聊),GroupChat(群聊)",
 * "messageId": "消息的唯一标识符",
 * "conversationId": "所属会话的唯一标识符",
 * "from": "发送方",
 * "to": "接收方",
 * "timestamp": "时间戳",
 * "body":{
 * "type":"消息体类型，包括，0.Text(文本),1.Image(图片),2.Location(位置),3.Voice(语音),4.Video(视频),5.File(文件)",
 * "text（type为0）": "消息内容",
 * "remotePath": "（type为1）大图remote路径（type为3）音频remote路径（type为4）视频remote路径（type为5）文件remote路径",
 * "localPath": "（type为1）大图local路径（type为3）音频local路径（type为4）视频local路径（type为5）文件local路径",
 * "thumbnailRemotePath": "（type为1）小图remote路径（type为4）第一帧缩略图remote路径（type为4）第一帧缩略图local路径",
 * "thumbnailLocalPath": "（type为1）小图local路径",
 * "latitude": "（type为2）纬度",
 * "longitude": "（type为2）经度",
 * "address": "（type为2）地址",
 * "fileLength": "（type为3）音频文件大小（type为4）视频文件大小（type为5）文件大小",
 * "duration":"（type为3）音频的时间长度"（type为4）视频的时间长度{
 * }
 */
//显示收的对方的消息
function showCommingMsg(data){
	messageId = data.messageId;
	if(isMessageExits(messageId)){
		return;
	}
	chatType = data.chatType;
	body_text = data.body.text;
	body_type = data.body.type;//0.Text(文本),1.Image(图片),2.Location(位置),3.Voice(语音),4.Video(视频),5.File(文件)
	if (chatType == "Chat") {
		if(data.from==herImId){
			setTimeLine4Dynamic(data.timestamp);//设置时间间隔线
			if(body_type=='0'){//文字
				appendOneMessage2End({
					template : her_text_template,
					userId : herUserId,
					text : body_text,
					logo : herLogo,
					messageId: messageId
				});
			}else if(body_type=='1'){//图片
				appendOneMessage2End({
					template : her_pic_template,
					userId : herUserId,
					text : "",
					pictrue : data.body.remotePath,//大图local路径
					logo : herLogo,
					messageId: messageId
				});
			}else if(body_type=='3'){//语音
				imHelper.storeUnReadAudioIds(messageId);//缓存未读语音messageId
				duration = data.body.duration;
				deviceone.print("在线收到-语音长度："+duration);
				if(duration>100){//因为IOS以ms为单位，andriod以s为单位
					duration = Math.round(duration/1000);
				}else if(duration==0){
					//因为IOS发送语音没有duration,所以暂且用文件大小来估算时长
					fileLength = data.body.fileLength;
					duration = Math.round(fileLength/10000)*2;
				}
				var duration4show = "";
				if(duration!=0){
					duration4show = duration;
				}
				appendOneMessage2End({
					template : her_audio_template,//模板 cell/left_audio.ui
					userId : herUserId,
					text : duration4show +"\"", //语音长度（毫秒,要转成秒）
					voiceLen : duration,
					voice : data.body.remotePath,//音频remote路径
					logo : herLogo,
					messageId: messageId,
					showNewAudio: true //未读语音
				});
				
			}
			chatList.refreshItems();
		}else{
			nf.toast("你有新的私信！");
			return;
		}
	}else{
		nf.toast("你有新的群聊消息！");
		return;
	}
	scroll2ListEnd();
}

/**
 * @param bodyType 0.Text(文本),1.Image(图片),2.Location(位置),3.Voice(语音),4.Video(视频),5.File(文件)
 * @param bodyText
 * @param bodyFile {path:xxx,len: xxx}
 */
function fireSendingMessage(bodyType,bodyText,bodyFile){
	var timestamp = new Date().getTime();//当前时间
	var msgBody = {type:bodyType,text:bodyText,remotePath:bodyFile.path,duration:bodyFile.len};//消息体body
	var message = {from:myImId,to:herImId,chatType:"Chat",timestamp:timestamp,body:msgBody};
	app.fire("im_sending_messages", message);//触发“发送消息”在消息页面显示最新的消息（我发送的）
	httpSilence.post(imUrl.url.message.sendMsgToUser,{"herUserId":""+herUserId}, function(data) {});
}

//即时聊天消息：时间间隔显示5分钟
function setTimeLine4Dynamic(longTime){
	var timeBalMin = (longTime-startTime)/1000/60;//分钟差量
	var longTimeCn = time.shortFormat(longTime);//时间格式化
	if(timeBalMin>5){
		startTime=longTime;//重置开始比较时间
		appendOneMessage2End({
			template : time_line_template,//模板cell/timeLine.ui
			time : longTimeCn
		});
		chatList.refreshItems();
	}				
}

//历史聊天消息：时间间隔显示5分钟
var startHisTime = new Date().getTime();
function setTimeLine4HistoryMsg(longTime){
	lastMsgTime = longTime;
	var timeBalMin = (startHisTime-longTime)/1000/60;//分钟差量
	var longTimeCn = time.shortFormat(longTime);//时间格式化
	if(timeBalMin>5){
		startHisTime=longTime;//重置开始比较时间
		insertOneMessage2Top({
			template : time_line_template,//模板cell/timeLine.ui
			time : longTimeCn
		});
		chatList.refreshItems();
	}				
}

//如果没有更早的历史消息，并且列表中有消息且第一行不是时间模板，就显是时间线
function setTimeLine4LastOneMsg(){
	if(chatListData.getCount()==0){
		return;
	}else{
		var firstMsg = chatListData.getOne(0);
		if(firstMsg.template == time_line_template){
			return;
		}
	}
	if(lastMsgTime==null){
		return;
	}
	var lastMsgTimeCn = time.shortFormat(lastMsgTime);//时间格式化
	insertOneMessage2Top({
		template : time_line_template,//模板cell/timeLine.ui
		time : lastMsgTimeCn
	});
	chatList.refreshItems();				
}


//判断消息是否已存在
function isMessageExits(vsMessageId){
	var isExists = false;
	for (var i = 0; i < chatListData.getCount(); i++) {
		var oneData = chatListData.getOne(i);
		if (oneData.messageId==vsMessageId) {//如果页面中有这条消息
			isExists = true;
			break;
		}
	}
	return isExists;
}

//下拉列表，加载更多历史消息
chatList.on("pull", function(data){
	page.hideKeyboard();
	if (data.state == 2) {
		loadMoreHistoryMessage(messageId4QueryLast);
		chatList.rebound();//复位【一定要做】
	}
});

//上拉列表，翻页数据
chatList.on("push", function(data){
	page.hideKeyboard();
	chatList.rebound();
});

var audioing = ui("audioing");
var frameAudio = ui("frameAudio");
frameAudio.startGif("source://image/audioing.gif",-1);
page.on("audioBox",function(data){
	audioing.visible = data;
})

//提示剩下录录音时长【倒数】
page.on("audioTimeLess",function(data){
	ui("aduioTooLong").visible = data.isShow;
	ui("lableTip").text = data.tip;
	ui("lableMin").text = data.lastMin;
})

//当播放语音后，这条消息的小红点去点
page.on("im_chat_page_remove_redtip",function(vsMessageId){
	for (var i = 0; i < chatListData.getCount(); i++) {
		var oneData = chatListData.getOne(i);
		if (oneData.messageId==vsMessageId) {
			oneData.showNewAudio = false;
			chatListData.updateOne(i, oneData);
			break;
		}
	}
})

/**
 * 显示消息
 * 在列表前面插入数据方式
 * @param msgList 要显示的消息数据list
 * @param isScroll2End 是否滚动到列表底部
 * @returns
 */
function showMessageBefore(msgList,isScroll2End){
	var len = msgList.length;
	for(var i=len-1;i>=0;i--){
		var oneMessage = msgList[i];
		messageId = oneMessage.messageId;
		if(messageId=="" || messageId ==null){
			continue;
		}
		if(isMessageExits(messageId)){
			continue;
		}
		timestamp = oneMessage.timestamp;
		from = oneMessage.from;
		to = oneMessage.to;		
		if(from==myImId && to==herImId){//我发的
			showMySendMsg4History(oneMessage);
		}else if(from==herImId && to==myImId){//他发的
			showHerSendMsg4History(oneMessage);
		}
		setTimeLine4HistoryMsg(timestamp);//设置时间间隔线
	}
	chatList.refreshItems();
	if(isScroll2End){
		scroll2ListEnd();
	}
}

//显示一条我发的历史消息
function showMySendMsg4History(oneMsg){
	messageId = oneMsg.messageId;
	timestamp = oneMsg.timestamp;
	body_type = oneMsg.body.type;//0.Text(文本),1.Image(图片),2.Location(位置),3.Voice(语音),4.Video(视频),5.File(文件)
	body_text = oneMsg.body.text;
	var pictruePath = oneMsg.body.thumbnailRemotePath;
	if(pictruePath==""){
		pictruePath = oneMsg.body.thumbnailLocalPath;
	}
	if(pictruePath==""){
		pictruePath = oneMsg.body.remotePath;
	}
	if(body_type=="0"){//文字
		insertOneMessage2Top({
			template : my_text_template,//模板 cell/right_text.ui
			text : body_text,
			logo : myLogo,
			messageId: messageId
		});
	}else if(body_type=="1"){//图片
		insertOneMessage2Top({
			template : my_pic_template,//模板 cell/right_pic.ui
			text : "",
			pictrue : pictruePath,
			logo : myLogo,
			messageId: messageId
		});
	}else if(body_type=="3"){//语音
		duration = oneMsg.body.duration;
		//deviceone.print("历史-语音长度："+duration);
		if(duration>100){//因为IOS以ms为单位，andriod以s为单位
			duration = Math.round(duration/1000);
		}else if(duration==0){
			//因为IOS发送语音没有duration,所以暂且用文件大小来估算时长
			fileLength = oneMsg.body.fileLength;
			duration = Math.round(fileLength/10000)*2;
		}
		var duration4show = "";
		if(duration!=0){
			duration4show = duration;
		}
		insertOneMessage2Top({
			template : my_audio_template,//模板 cell/right_audio.ui
			text : duration4show +"\"", //语音长度（秒）
			voiceLen : duration,
			voice : oneMsg.body.remotePath,//语音remote路径(用于显示)
			logo : myLogo,
			messageId: messageId
		});
	}
}

//显示一条对方发的历史消息
function showHerSendMsg4History(oneMsg){
	messageId = oneMsg.messageId;
	timestamp = oneMsg.timestamp;
	body_type = oneMsg.body.type;//0.Text(文本),1.Image(图片),2.Location(位置),3.Voice(语音),4.Video(视频),5.File(文件)
	body_text = oneMsg.body.text;
	var pictruePath = oneMsg.body.thumbnailRemotePath;
	if(pictruePath==""){
		pictruePath = oneMsg.body.thumbnailLocalPath;
	}
	if(pictruePath==""){
		pictruePath = oneMsg.body.remotePath;
	}
	if(body_type=="0"){//文字
		insertOneMessage2Top({
			template : her_text_template,//模板 cell/left_text.ui
			userId : herUserId,
			text : body_text,
			logo : herLogo,
			messageId: messageId
		});
	}else if(body_type=="1"){//图片
		insertOneMessage2Top({
			template : her_pic_template,//模板 cell/left_pic.ui
			userId : herUserId,
			text : "",
			pictrue : pictruePath,//图片remote路径(用于显示)
			logo : herLogo,
			messageId: messageId
		});
	}else if(body_type=="3"){//语音
		duration = oneMsg.body.duration;
		if(duration>100){//因为IOS以ms为单位，andriod以s为单位
			duration = Math.round(duration/1000);
		}else if(duration==0){
			//因为IOS发送语音没有duration,所以暂且用文件大小来估算时长
			fileLength = oneMsg.body.fileLength;
			duration = Math.round(fileLength/10000)*2;
		}
		var showNewAudio = false; //未读语音
		if(imHelper.isUnReadAudio(messageId)){
			showNewAudio = true;//加上未播放红点
		}
		var duration4show = "";
		if(duration!=0){
			duration4show = duration;
		}
		insertOneMessage2Top({
			template : her_audio_template,//模板 cell/left_audio.ui
			userId : herUserId,
			text : duration4show +"\"", //语音长度（秒）
			voiceLen : duration,
			voice : oneMsg.body.thumbnailLocalPath,//语音remote路径(用于显示)
			logo : herLogo,
			messageId: messageId,
			showNewAudio: showNewAudio
		});
	}
}
//插入一条消息到头部
function insertOneMessage2Top(message){
	chatListData.addOne(message,0);
}
//追加一条消息到尾部
function appendOneMessage2End(message){
	chatListData.addOne(message);
}